<template>
	<view class="ve-picker-wrapper">
		<view class="ve-picker-trigger" @tap="showPopUp">
			<slot />
		</view>
		<ve-popup v-model="visible" mode="bottom" @close="cancel">
			<view class="ve-picker-box">
				<view class="ve-picker-box-head">
					<view class="item-btn" @tap="cancel">取消</view>
					<view class="item-btn confirm-btn" @tap="handleConfirm">确定</view>
				</view>
				<view class="ve-picker-box-body">
					<picker-view class="ve-picker-view" indicator-style="height: 44px;" :value="valueArr" :immediate-change="true"
						@change="handleChange" v-if="Array.isArray(range) && range.length > 0">
						<picker-view-column>
							<view class="column-item" v-for="(item, index) in range" :key="index">
								{{ rangeKey ? item[rangeKey] : item }}
							</view>
						</picker-view-column>
					</picker-view>
					<view v-else>
						<ve-empty :marginTop="50" />
					</view>
				</view>
			</view>
		</ve-popup>
	</view>
</template>

<script>
export default {
	name: "ve-picker-index",
	props: {
		value: [String, Number],
		range: {
			type: Array,
			default: () => {
				return []
			}
		},
		rangeKey: {
			type: String,
		},
		disabled: {
			type: Boolean,
			default: false
		}
	},
	watch: {
		value: {
			handler() {
				// 兼容初始值为 undefined 的情况
				let initValue = this.value || 0
				this.valueArr = [initValue]
				this.confirmValue = [initValue]
			},
			immediate: true
		}
	},
	data() {
		return {
			visible: false,
			valueArr: [0],
			confirmValue: [],
		}
	},
	methods: {
		showPopUp() {
			if (!this.disabled) {
				this.visible = true
			}
		},
		handleConfirm() {
			this.confirmValue = this.valueArr;
			let val = this.confirmValue[0]
			this.$emit('change', {
				detail: {
					value: val
				},
				target: {
					value: val
				}
			})
			this.close();
		},
		close() {
			this.valueArr = this.confirmValue;
			this.visible = false
		},
		cancel() {
			this.$emit('cancel')
			this.close()
		},
		handleChange(e) {
			this.valueArr = e.detail.value;
		}
	}
}
</script>


<style lang="scss" scoped>
.ve-picker-box {
	// 安全底部距离
	padding-bottom: 0;
	padding-bottom: constant(safe-area-inset-bottom);
	padding-bottom: env(safe-area-inset-bottom);

	&-head {
		width: 100%;
		height: 120rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		color: #1F2334;
		font-size: 32rpx;
		line-height: 44rpx;

		.item-btn {
			padding: 28rpx;
		}

		.confirm-btn {
			font-weight: 500;
			color: #3072F6;
		}
	}

	&-body {
		height: 40vh;

		.column-item {
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 32rpx;
			padding: 0 8rpx;
		}
	}
}

.ve-picker-view {
	height: 100%;
	box-sizing: border-box;
}
</style>
